<?php

class Hall extends BaseHall
{
	public static function getImages($dir)
	{
    $images = array();

    foreach (glob(rtrim($dir, '/\\') . '/thumb_*', GLOB_BRACE) as $match)
    {
      $images[] = substr($match, strrpos($match, '_') + 1);
    }

    return $images;
	}

	public function getGallery()
	{
    $dir  = AgaviConfig::get('core.uploads_dir') . '/halls/' . $this->id;
    $path = AgaviConfig::get('app.path') . '/uploads/halls/' . $this->id . '/';

    $gallery = array();

    foreach (Hall::getImages($dir) as $image)
    {
      $thumbInfo = getimagesize($dir . '/thumb_' . $image);
      $imageInfo = getimagesize($dir . '/' . $image);

      $gallery[] = array(
        'thumb'     => $path . 'thumb_' . $image,
        'thumbSize' => $thumbInfo[3],
        'image'     => $path . $image,
        'width'     => $imageInfo[0],
        'height'    => $imageInfo[1]
      );
    }

    return $gallery;
	}

	public function getReservations($from, $to, $status = null)
	{
		$tm = AgaviContext::getInstance()->getTranslationManager();

		$q = Doctrine_Query::create()
			->select('r.id, r.fromTime, r.toTime, r.status, u.name AS creator')
			->from('Reservation r')
			->innerJoin('r.User u')
     	->where('r.hallId=? AND r.fromTime >= ? AND r.toTime <= ?', array($this->id, $from, $to))
			->orderBy('r.fromTime ASC');

		if ($status !== null)
		{
			$q->andWhere('r.status=?', $status);
   	}

		$from         = strtotime(date('Y-m-d', $from));
   	$secondsInDay = 24 * 3600;

		for ($day = 0; $day < 7; ++$day) $reservations[$from + $day * $secondsInDay] = array();

  	foreach ($q->fetchArray() as $row)
		{
			$day = strtotime(date('Y-m-d', $row['fromTime']));

			if (!isset($reservations[$day])) $reservations[$day] = array();

			$reservations[$day][] = array(
				'id'         => $row['id'],
				'from'       => $tm->_d((int)$row['fromTime'], 'short_date'),
				'to'         => $tm->_d((int)$row['toTime'], 'short_date'),
				'time'       => round(($row['toTime'] - $row['fromTime']) / 60),
				'creator'    => $row['creator'],
				'status'     => $row['status'],
				'statusText' => Reservation::mapStatusToText($row['status']),
				'actions'    => Reservation::createActionsFromStatus($row['status']),
			);
		}

		return $reservations;
	}
}